package spil;

import desktop_resources.GUI;

public class Game {
	static int loseCount;
	static Dice d1 = new Dice();
	static Gameboard board = new Gameboard();
	static Player[] players;
	
	public static void main(String[] args) {
		initiate();
		while(true) {
			for(int i = 0; i < players.length; i++) {
				if(!players[i].hasLost())
					playerTurn(players[i]);
				for(int j = 0; j < players.length; j++)
					GUI.setBalance(players[i].getName(), players[i].getBalance());
			}
			if (loseCount == players.length - 1)
				break;
		}
		int winner = checkWinner();
		GUI.getUserButtonPressed(players[winner]+" has won.\nWell done", "ok");
	}

	public static void initiate() {
		board.setFields();
		board.setOwnables();
		int pnumber = GUI.getUserInteger("Hvor mange spillere?", 2, 6);
		players = new Player[pnumber];
		for(int i = 0; i < pnumber; i++) {
			String name = GUI.getUserString("spiller " + (i+1) + "s navn");
			players[i] = new Player(i+1, name);
			GUI.addPlayer(name, 0);
			GUI.setCar(1, name);
			GUI.setBalance(name, players[i].getBalance());
		}
	}
	
	public static void playerTurn(Player p) {
		GUI.getUserButtonPressed(p + "'s tur", "ok");
		d1.roll();
		GUI.removeCar(p.getPosition(), p.getName());
		if(!p.getJailed())
			p.move(d1.getSum());
		GUI.setDice(d1.getd1(), d1.getd2());
		GUI.setCar(p.getPosition(), p.getName());
		board.getField(p.getPosition()).landOnField(p);
		if(p.getBalance() <= 0) {
			loseCount++;
			p.lose();
			loseProperty(p);
			p.getAccount().setBalance(0);
			GUI.removeCar(p.getPosition(), p.getName());
		}
	}
	
	public static void loseProperty(Player p) {
		for(int i = 0; i < board.getOwnables().length; i++) {
			board.getOwnables()[i].lose(p);
		}
	}
	
	public static int checkWinner() {
		for(int i = 0; i < players.length; i++) {
			if(!players[i].hasLost())
				return i;
		}
		return 0;
	}
}
